package cc.rengu.redp.flowable.delegate;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 缓存流程相关的delegate程序，供前端图形化配置
 */
@Service
public class DelegateManager implements ApplicationListener<ContextRefreshedEvent> {

    private final static Map<String, String> DELEGATES = new HashMap<>();

    private static String reClassName(String simpleClassName) {
        StringBuilder sb = new StringBuilder(simpleClassName);
        sb.setCharAt(0, Character.toLowerCase(sb.charAt(0))); // 类名首字母转为小写
        return sb.toString();
    }

    public static void addDelegate(Class<? extends BaseDelegate> baseDelegateClass, String delegateName) {
        DELEGATES.put(reClassName(baseDelegateClass.getSimpleName()), baseDelegateClass.getSimpleName() + "-" + delegateName);
    }

    public static Map<String, String> getAll() {
        return DELEGATES;
    }

    /**
     * springboot启动时自动注册继承自BaseDelegate的类
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //获取Spring容器
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        //获取全部BaseDelegate的衍生类
        Map<String, BaseDelegate> beans = applicationContext.getBeansOfType(BaseDelegate.class);

        for (Map.Entry<String, BaseDelegate> en : beans.entrySet()) {
            DelegateManager.addDelegate(en.getValue().getClass(), en.getValue().delegateSimpleDescription());
        }
    }
}
